package com.victor.controller.soncompany_controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.victor.entity.Administrator;
import com.victor.entity.Department;
import com.victor.entity.soncompany.Soncompany;
import com.victor.service.SoncompanyService;
import com.victor.utils.Msg;

/**
 * 子公司管理
 * 
 * @author zhangbin
 *
 */
@RestController
@RequestMapping("/soncompany")
public class SoncompanyController {

	@Autowired
	private SoncompanyService service;

	// 添加子公司(省级)返回id
	// son_grade;//公司等级 0省级 1 市级
	// higher_company_id;//上级公司id 如果该公司等级为省级 上级公司id为0 如果公司为市级公司 则上级为省级公司id
	@RequestMapping("/addSonCompany")
	public Msg addSonCompany(@RequestBody Soncompany soncompany) {
		boolean insResult = service.addSonCompany(soncompany);
		if (insResult) {
			if (soncompany.getDepartments() != null && soncompany.getDepartments().size() > 0) {
				// 遍历部门信息
				for (Department departments : soncompany.getDepartments()) {
					if (soncompany.getHigher_company_id().equals("0")) {
						departments.setJoincompany_id("0");
					} else {
						departments.setJoincompany_id(String.valueOf(soncompany.getId()));
					}
					// 添加部门
					service.addSonCompanydepartments(departments);
				}
			}
			return Msg.success();
		}
		return Msg.fail();
	}

	// 查询公司本部员工
	@RequestMapping("/getOwnEmployee")
	public Msg getOwnEmployee(String soncompanyid) {
		List<Administrator> employees = service.getOwnEmployee(soncompanyid);
		return Msg.success().add("employees", employees);
	}

	// 查询下属公司列表
	@RequestMapping("/getSubordinateCompany")
	public Msg getSubordinateCompany(String soncompanyid) {
		List<Soncompany> soncompanys = service.getSubordinateCompany(soncompanyid);
		return Msg.success().add("soncompanys", soncompanys);
	}

	// 修改公司详情
	@RequestMapping("/updSoncompany")
	public Msg updSoncompany(@RequestBody Soncompany soncompany) {

		boolean insResult = service.updSoncompany(soncompany);
		if (insResult) {
			if (soncompany.getDepartments() != null && soncompany.getDepartments().size() > 0) {

				// 删除所有本公司的原部门
				service.delFormerDepartment(soncompany.getId());

				// 遍历部门信息
				for (Department departments : soncompany.getDepartments()) {
					if (soncompany.getHigher_company_id().equals("0")) {
						departments.setJoincompany_id("0");
					} else {
						departments.setJoincompany_id(String.valueOf(soncompany.getId()));
					}
					// 添加部门
					service.addSonCompanydepartments(departments);
				}
			}
			return Msg.success();
		}
		return Msg.fail();
	}

}
